package main.Primavera;

import com.primavera.PrimaveraException;
import com.primavera.ServerException;
import com.primavera.integration.client.bo.BOIterator;
import com.primavera.integration.client.bo.BusinessObjectException;
import com.primavera.integration.client.bo.object.User;
import com.primavera.integration.common.DatabaseInstance;
import com.primavera.integration.network.NetworkException;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;

public class loginForm extends JDialog {

    public LoginFunctions loginFnc;
    private javax.swing.JTextField inputLogin;
    private javax.swing.JPasswordField inputPassword;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox selectDB;

    //XML-конфиги
    private JLabel labelServer;
    private JButton xmlConfigButton;
    private static JComboBox listServer;
    public static DefaultComboBoxModel listServerModel;

    public static void main(String args[]) {

    }

    public loginForm(LoginFunctions loginFunc) {
        this.loginFnc = loginFunc;
        setModal(true);
        initComponents();
        centerOnScreen(this);
        this.setResizable(false);

        showDBs();
    }

    private void centerOnScreen(Container win) {
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        Rectangle bounds = gd.getDefaultConfiguration().getBounds();
        Dimension winDim = win.getSize();
        Point loc = new Point((bounds.width - winDim.width) / 2, (bounds.height - winDim.height) / 2);
        win.setLocation(loc);
    }

    private void showDBs() {
        selectDB.removeAllItems();
        loginFnc.setConnectionInfo(getConnectionInfo());
        System.out.println("sHost: " + loginFnc.sHost);
        if (loginFnc.sHost != null) {
            DatabaseInstance[] dbInstances = loginFnc.getDatabaseInstances();

            if ((dbInstances == null) || (dbInstances.length == 0)) {
                JOptionPane.showMessageDialog(null, "No database instances were found", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (DatabaseInstance dbInstance : dbInstances) {
                selectDB.addItem(dbInstance);
            }
        } else {
            selectDB.removeAllItems();
            ConfigServerList configServerList = new ConfigServerList();
            configServerList.openServerList(listServerModel);
        }

    }

    //Изменения в получении параметров сервера Prim
    private static LoginFunctions.ConnectionInfo getConnectionInfo() {
        LoginFunctions.ConnectionInfo connInfo = new LoginFunctions.ConnectionInfo();

        ConfigXML configXML = new ConfigXML();
        String[] serverParam = configXML.getChooseConfig(String.valueOf(listServer.getSelectedItem()));

        System.out.println("test " + serverParam[0]);

        if (serverParam[0] == null) {
        connInfo = null;
        } else {
            connInfo.sCallingMode = "Remote";
            connInfo.sHost = serverParam[1];
            connInfo.iPort = Integer.parseInt(serverParam[2]);
            connInfo.iRMIServiceMode = 1;
        }
        System.out.println(connInfo);
        return connInfo;
    }

    private LoginFunctions.LoginInfo getLoginInfo() {
        LoginFunctions.LoginInfo loginInfo = new LoginFunctions.LoginInfo();
        loginInfo.sUserName = inputLogin.getText().trim();

        loginInfo.sPassword = new String(inputPassword.getPassword()).trim();
        DatabaseInstance dbi = (DatabaseInstance) selectDB.getSelectedItem();

        if (dbi == null) {
            JOptionPane.showMessageDialog(this, "No database instance is selected", "Error", JOptionPane.ERROR_MESSAGE);
            selectDB.requestFocus();
            return null;
        }

        loginInfo.sDatabaseId = dbi.getDatabaseId();

        return loginInfo;
    }

    private void tryToLogin() {

        loginFnc.setLoginInfo(getLoginInfo());

        if (loginFnc.sUserName.length() == 0) {
            JOptionPane.showMessageDialog(this, "Имя пользователя не может быть пустым.", "Ошибка", JOptionPane.ERROR_MESSAGE);
            inputLogin.requestFocus();

            return;
        }

        try {
            loginFnc.login();
        } catch (PrimaveraException e) {
            //e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Введеное имя пользователя или пароль не найдено.", "Ошибка", JOptionPane.ERROR_MESSAGE);

            return;
        }

        dispose();
    }

    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        inputLogin = new javax.swing.JTextField();
        inputPassword = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        selectDB = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        //Компоненты XML-конфига. Начало.
        ConfigXML configXML = new ConfigXML();

        labelServer = new JLabel("Server Name");
        xmlConfigButton = new JButton();
        listServerModel = configXML.serverListBoxModel();

        //Список серверов
        listServer = new JComboBox(listServerModel);
        listServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                showDBs();
                System.out.println(listServer.getSelectedItem());
            }
        });

        //Кнопка вызова диалога работы с серверами Prim

        xmlConfigButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ConfigServerList configServerList = new ConfigServerList();
                configServerList.openServerList(listServerModel);
            }
        });

        labelServer.setFont(new Font("Calibri", 0, 12));
        labelServer.setHorizontalAlignment(SwingConstants.RIGHT);

        xmlConfigButton.setIcon(new ImageIcon(getClass().getResource("configButton_grey.png")));

        //Компоненты XML-конфига. Конец.

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Login to Primavera P6");
        setResizable(false);
        setType(java.awt.Window.Type.UTILITY);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        inputLogin.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        inputLogin.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputLoginKeyPressed(evt);
            }
        });

        inputPassword.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        inputPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputPasswordKeyPressed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jButton1.setText("Login");
        jButton1.setMargin(new java.awt.Insets(6, 14, 6, 14));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        selectDB.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        selectDB.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
        selectDB.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N
        jLabel1.setText("Вход в Primavera P6");

        jSeparator1.setBackground(java.awt.SystemColor.control);
        jSeparator1.setForeground(java.awt.SystemColor.activeCaptionBorder);

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Login Name");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Password");

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Database Name");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap(52, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(labelServer, GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addGap(16, 16, 16)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(inputLogin, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(inputPassword, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(listServer, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(selectDB, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(16, 16, 16)
                                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                        .addComponent(xmlConfigButton, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE))
                                .addGap(16, 16, 16))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(56, 56, 56)
                                .addComponent(jLabel1)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(jLabel1)
                                .addGap(7, 7, 7)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(inputLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel2))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(inputPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                        .addComponent(xmlConfigButton, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(listServer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(labelServer))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(selectDB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel4))
                                .addGap(18, 18, 18)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(30, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 430, 310));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        tryToLogin();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void inputLoginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputLoginKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            inputPassword.requestFocus();
        }
    }//GEN-LAST:event_inputLoginKeyPressed

    private void inputPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputPasswordKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            tryToLogin();
        }
    }//GEN-LAST:event_inputPasswordKeyPressed

}
